package net.gz01.wallet.web.noitfy;


import net.gz01.util.ZOHttp;
import net.gz01.util.ZOJson;
import net.gz01.util.ZOLog;
import net.gz01.util.ZOMD5;
import net.gz01.wallet.web.config.SystemConfig;
import net.gz01.wallet.web.model.TradeOrder;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.concurrent.Callable;

public class NotifyProcessThread implements Callable<List<NotifyThreadData>> {

	private static final int MAX_PUSH = 30;

	private Vector<NotifyThreadData> dataList = new Vector<>();

	public NotifyProcessThread(Vector<NotifyThreadData> dataList) {
		this.dataList = dataList;
	}

	@Override
	public List<NotifyThreadData> call() {
		NotifyReq notifyReq;
		NotifyThreadData data;
		List<NotifyThreadData> needRemoveList = new ArrayList<>();
		// 每个线程循环分配到的集合
		for (int i = 0; i < dataList.size(); i++) {
			data = dataList.get(i);
			if(data.getCurrentPushCount() >= MAX_PUSH){
				needRemoveList.add(data);
				continue;
			}

			// 开始推送 判断是交易订单还是代付订单
			notifyReq = data.getReq();
			String safeKey = SystemConfig.config.get("apiyl_key");
			notifyReq.setSign(ZOMD5.sortSign(notifyReq, safeKey));
			String sendResult = "";
			try {
				//5秒推送和接收
				Map<String, String> map = ZOJson.toTreeMap(ZOJson.toString(notifyReq));
				sendResult = ZOHttp.postKeyValue(notifyReq.getNotifyUrl(), map,"UTF-8");
			} catch (Exception e) {
				data.setCurrentPushCount(data.getCurrentPushCount() + 1);
				ZOLog.api.error("订单号=" + notifyReq.getMallOrderNo() + "通知商户发生异常,当前次数="+data.getCurrentPushCount()+"异常信息->",e);
				continue;
			}

			if (("SUCCESS").equalsIgnoreCase(sendResult)) {
				TradeOrder.dao.updateNotifyStatus(notifyReq.getMallOrderNo(),true);
				// 放入需要删除的集合中,返回到主线程进行删除
				needRemoveList.add(data);
				System.out.println("通知商户成功,订单号=" + notifyReq.getMallOrderNo());
			} else {
				data.setCurrentPushCount(data.getCurrentPushCount() + 1);
				System.out.println("通知商户失败,订单号=" + notifyReq.getMallOrderNo() + ",返回->" + sendResult + "->当前推送次数=" + data.getCurrentPushCount());
			}

		}
		return needRemoveList;
	}

}
